<?php
// +----------------------------------------------------------------------
// | Longbing [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright Chengdu longbing Technology Co., Ltd.
// +----------------------------------------------------------------------
// | Website http://longbing.org/
// +----------------------------------------------------------------------
// | Sales manager: +86-13558882532 / +86-13330887474
// | Technical support: +86-15680635005
// | After-sale service: +86-17361005938
// +----------------------------------------------------------------------
namespace app\shortvideo\controller;

use app\AdminRest;
use app\shortvideo\model\Shortvideo;
use app\shortvideo\model\ShortvideoBrowse;
use app\shortvideo\model\ShortvideoCompany;
use app\shortvideo\model\ShortvideoCount;
use app\shortvideo\model\ShortvideoVisitors;
use think\App;

/**
 **@author lichuanming
 * @DataTime: 2020/5/19 14:47
 * Class AdminCount
 * @package app\shortvideo\controller
 * @功能说明：数据结算
 */
class AdminCount extends AdminRest{

    protected $model; #shortvideo 模型
    protected $model_browse; #shortvideo_browse 模型
    protected $model_visitors; #shortvideo_visitors 模型
    protected $shortvideo_company_model; #shortvideo_company 模型
    protected $count_model; #shortvideo_count 模型
    protected $page_size;

    private $initial_time; //所有数据的开始时间

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model          = new Shortvideo();
        $this->model_browse   = new ShortvideoBrowse();
        $this->model_visitors = new ShortvideoVisitors();
        $this->shortvideo_company_model = new ShortvideoCompany();

        $this->count_model = new ShortvideoCount();


        if(isset($this->_param['limit'])){
            $this->page_size = $this->_param['limit'];
        }elseif (isset($this->_input['limit'])){
            $this->page_size = $this->_param['limit'];
        }else{
            $this->page_size = 10;
        }

        $initial_time = $this->model_browse->where('uniacid', '=', $this->_uniacid)
            ->order('create_time','asc')->find();
        if($initial_time){
            $initial_time = $initial_time['create_time'];
            //数据开始时间 查询周期不得小于该时间
            $this->initial_time = strtotime(date('Y-m-d',$initial_time));
        }else{
            $this->initial_time = strtotime(date('Y-m-d',time()));
        }
    }

    //数据开始时间 -- 初始化时间
    public function initial_time(){
        return $this->success(['initial_time'=>$this->initial_time]);
    }

    /**
     **@param $begin_time
     * @param $end_time
     * @功能说明: 将还未统计的数据 进行统计并写入
     * @author lichuanming
     * @DataTime: 2020/5/21 11:42
     */
    public function statisticalData($begin_time,$end_time){
        $begin_time = $begin_time < $this->initial_time ? $this->initial_time : $begin_time;
        $end_time = strtotime("-1 day"); //最多到昨天

        $where = [
            ['uniacid', '=', $this->_uniacid],
            ['date', '>=', $begin_time],
            ['date', '<=', $end_time],
        ];
        $count_list = $this->count_model->where($where)->column('day');
        //将还未统计的数据 进行统计并存入数据库
        $add_list = [];
        for($i = $begin_time; $i <= $end_time; $i += 86400)
        {
            $ThisDate=date("Y-m-d",$i);
            if(!in_array($ThisDate,$count_list) && $ThisDate != date('Y-m-d',time())){
                $countData = $this->daycount($ThisDate);
                $countData['uniacid'] = $this->_uniacid;
                $add_list[] = $countData;
            }
        }
        if(!empty($add_list)){
            $this->count_model->addCount($add_list);
        }
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/19 14:49
     * @功能说明: 统计所有数据
     */
    public function allcout(){
        $week_where = $where = [
            ['uniacid' ,'=' ,$this->_uniacid]
        ];

        //获取本周开始 -- 结束时间
        $beginWeek = mktime(0,0,0,date("m"),date("d")-date("w")+1,date("Y"));
        $endWeek = mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"));

        $week_where[] = ['create_time', '>=', $beginWeek];//本周开始时间
        $week_where[] = ['create_time', '<=', $endWeek];//本周结束时间

        //查询基本数据
        $resData = $this->publicCount($where,true,true);
        //数据单位换算 保留一位小数不四舍五入
        foreach ($resData as $k=>$item){
            if ($item >= 100000000) {
                $resData[$k] = floor(($item / 100000000)*10)/10 .'亿';
            }else{
                if ($item >= 10000) {
                    $resData[$k] = floor(($item / 10000)*10)/10 ."万";
                }
            }
        }

        //视频总数
        $resData['video_num'] =  $this->model->where([
            ['uniacid','=',$this->_uniacid],
            ['status','<>','-1'],
        ])->count();

        //本周数据
        $week_where[] = ['type', '=', 1];
        $resData['week_visitor_num']  = $this->model_visitors->getCount($week_where,''); //本周获客总次数
        $week_where[] = ['first','=',1];
        $resData['week_visitor_user'] = $this->model_visitors->getGroupCount($week_where); //本周获客总人数

        $dayCount = $this->daycount(); //获取今天的数据
        //今日新增
        $resData['day_visitor_num']   = $dayCount['visitor_num'];
        $resData['day_visitor_user']  = $dayCount['visitor_user'];

        return $this->success($resData);
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/21 9:44
     * @功能说明: 统计图表 --
     */
    public function count_table(){
        $param = $this->_param;
        $type  = isset($param['type'])?$param['type']:1;
        $Date_begin = isset($param['start_time'])?$param['start_time']:false; //前端请求的开始时间
        $Date_end   = isset($param['end_time'])?$param['end_time']:false; //前端请求的结束id时间

        $weekarray=array("周日","周一","周二","周三","周四","周五","周六"); //星期几的数组

        $begin_time = ''; //开始时间
        $end_time = ''; //结束时间

        $resData = [];
        switch ($type){
            case 1: //今日
            case 2: //昨日
                $date = $type == 2?date('Y-m-d',strtotime("-1 day")):0;
                $dayCount = $this->daycount($date); //获取某一天的数据
                $resData[] = [
                    'week' => $weekarray[date("w",$date?strtotime($date):time())], //星期几
                    'day' => date('m-d',strtotime($dayCount['day'])), //月日
                    'year' => date('Y',strtotime($dayCount['day'])), //年
                    'visitor_num' => $dayCount['visitor_num'], //获客次数
                    'visitor_user' => $dayCount['visitor_user'], //获客人数
                ];
                return $this->success($resData);
                break;
            case 3: //近七天 包含今天
            case 4: //近30天 包含今天
                $begin = strtotime(date('Y-m-d',$type == 3?strtotime("-7 day"):strtotime("-30 day")));
                $end_time = time();
                break;
            case 5: //自定义 时间查询
                $begin = strtotime($Date_begin);
                $end_time = strtotime($Date_end . '23:59:59');
                break;
        }

//        $begin_time = strtotime(date('Y-m-d',$begin<$this->initial_time?$this->initial_time:$begin)); //获取凌晨时间
        $begin_time = strtotime(date('Y-m-d',$begin)); //获取凌晨时间
        $where = [
            ['uniacid', '=', $this->_uniacid],
            ['date', '>=', $begin_time],
            ['date', '<=', $end_time],
        ];
        $this->statisticalData($begin_time,$end_time);

        $count_list = $this->count_model->countList($where,$this->page_size,'date asc');
        if(!empty($count_list['data'])){
            foreach ($count_list['data'] as $item){
                $resData[] = [
                    'week' => $weekarray[date("w",$item['date'])],
                    'day' => date('m-d',strtotime($item['day'])), //月日
                    'year' => date('Y',strtotime($item['day'])), //年
                    'visitor_num' => $item['visitor_num'],
                    'visitor_user' => $item['visitor_user'],
                ];
            }
        }

        //判断是否查询到当天
        if(date('Y-m-d',time()) >= date('Y-m-d',$begin_time)  && date('Y-m-d',time()) <= date('Y-m-d',$end_time)){
            $dayCount = $this->daycount(); //获取某一天的数据
            $resData[] = [
                'week' => $weekarray[date("w",time())], //星期几
                'day' => date('m-d',strtotime($dayCount['day'])), //月日
                'year' => date('Y',strtotime($dayCount['day'])), //年
                'visitor_num' => $dayCount['visitor_num'], //获客次数
                'visitor_user' => $dayCount['visitor_user'], //获客人数
            ];
        }

        //补充一些无意义的数据
        if(($type == 3 && count($resData) < 7) || ($type == 4 && count($resData) < 30)){
            $forNum = $type == 3?7:30;
            for($i = count($resData) ; $i < $forNum ; $i ++){
                $th_time = strtotime("-{$i} day");
                $resData[] =  [
                    'week' => $weekarray[date("w",$th_time)], //星期几
                    'day' => date('m-d',$th_time), //月日
                    'year' => date('Y',$th_time), //年
                    'visitor_num' => 0, //获客次数
                    'visitor_user' => 0, //获客人数
                ];
            }
        }elseif(count($resData) < 30 && $type == 5) {
            for($i = $begin_time; $i <= $end_time; $i += 86400)
            {
                $ThisDate=date("Y-m-d",$i);
                if(!in_array($ThisDate,$resData) && $ThisDate != date('Y-m-d',time())){
                    $th_time = strtotime($ThisDate);
                    $resData[] =  [
                        'week' => $weekarray[date("w",$th_time)], //星期几
                        'day' => date('m-d',$th_time), //月日
                        'year' => date('Y',$th_time), //年
                        'visitor_num' => 0, //获客次数
                        'visitor_user' => 0, //获客人数
                    ];
                }
            }
        }

        $distance = [];
        foreach ($resData as $key => $row) {
            $distance[$key] = $row['day'];
        }
        if(!empty($distance)){
            array_multisort($distance, SORT_ASC, $resData);
        }
        return $this->success($resData);
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/20 9:45
     * @功能说明: 统计列表
     */
    public function count_list(){
        $Date_begin = isset($this->_param['start_time'])?$this->_param['start_time']:'';
        $Date_end   = isset($this->_param['end_time'])?$this->_param['end_time']:'';

        $Date_begin = $Date_begin?$Date_begin:date('Y-m-d',$this->initial_time);
        $Date_end   = $Date_end?$Date_end:date('Y-m-d',time());

        $order    = isset($this->_param['order'])?$this->_param['order']:''; //需要进行排序的字段
        $By       = isset($this->_param['by'])?$this->_param['by']:''; //排序方式  asc  desc
        $order = $order?$order:'date';
        $By = $By?$By:'desc';


        if(!$Date_begin && !$Date_end){
            return $this->error('参数错误！');
        }
        #转化为时间戳
        $Date_begin_time = strtotime($Date_begin);
        $Date_end_time = strtotime($Date_end . '23:59:59');

        $Date_begin_time = $Date_begin_time<$this->initial_time?$this->initial_time:$Date_begin_time;
        $Date_begin_time = strtotime(date('Y-m-d',$Date_begin_time));

/*        $Date_begin_time = $this->initial_time;
        $Date_end_time = time();*/
        $where = [
            ['uniacid', '=', $this->_uniacid],
            ['date', '>=', $Date_begin_time],
            ['date', '<=', $Date_end_time],
        ];
        $this->statisticalData($Date_begin_time,$Date_end_time);

        //数据查询 --
        $list = $this->count_model->countList($where,$this->page_size,$order.' '.$By);

        $list['start_time'] = strtotime($Date_begin);
        $list['end_time'] = $Date_end_time;

        return $this->success($list);
    }


    /**
     **@param int $date yy-mm-dd
     * @功能说明: 获取某一天的数据 默认当天
     * @author lichuanming
     * @DataTime: 2020/5/20 9:32
     */
    public function daycount($date = 0){
        $date = $date?$date:date('Y-m-d',time());

        $day_time = strtotime($date);
        $begin_time = mktime(0,0,0,date('m',$day_time),date('d',$day_time),date('Y',$day_time)); //开始时间
        $end_time = $begin_time + (24*60*60 - 1); //结束时间

        $where = [
            ['uniacid', '=', $this->_uniacid],
            //拼接查询时间
            ['create_time', '>=', $begin_time],
            ['create_time', '<=', $end_time],
        ];
        //获取基本数据
        $count = $this->publicCount($where,true,true,true,true,true);
        $count['day'] = $date;
        $count['date'] = $day_time<0?0:$day_time;
        return $count;
    }


    /**
     **@author lichuanming
     * @DataTime: 2020/5/19 14:48
     * @功能说明:单一视频数据结算
     */
    public function video(){
        $video_id = isset($this->_param['video_id'])?$this->_param['video_id']:false;
        if(!$video_id){
            return $this->error('参数错误！');
        }
        $where = [
            ['video_id' ,'=' ,$video_id],
            ['uniacid' ,'=' ,$this->_uniacid],
        ];
        $resData = $this->publicCount($where,true,true);
        foreach ($resData as $k=>$item){
            if ($item >= 100000000) {
                $resData[$k] = floor(($item / 100000000)*10)/10 .'亿';
            }else{
                if ($item >= 10000) {
                    $resData[$k] = floor(($item / 10000)*10)/10 ."万";
                }
            }
        }

        $resData['title'] = $this->model->where([['id' ,'=' ,$video_id],['uniacid' ,'=' ,$this->_uniacid]])->value('title');

        return $this->success($resData);
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/19 15:45
     * @功能说明: 用户/员工列表
     */
    public function userList(){
        $type = isset($this->_input['type'])?$this->_input['type']:1; //数据类型 1.员工  2.客户
        $video_id = isset($this->_input['video_id'])?$this->_input['video_id']:false;

        $job = isset($this->_input['job'])?$this->_input['job']:0;
        $name = isset($this->_input['name'])?$this->_input['name']:'';

        $order    = isset($this->_input['order'])?$this->_input['order']:''; //需要进行排序的字段
        $By       = isset($this->_input['by'])?$this->_input['by']:''; //排序方式  asc  desc

        if(!$video_id){
            return $this->error('参数错误！');
        }
        $where = [
            ['b.video_id' ,'=' ,$video_id],
            ['a.uniacid' ,'=' ,$this->_uniacid],
        ];

        if($type == 1){
            if($name) {
                $where[] = ['a.name|g.nickName', 'like', "%{$name}%"];
            }
            if($job){
                $where[] = ['f.id', '=', $job];
            }
            if(!empty($this->_input['company'])){
                $company = $this->_input['company'];
                $company_id = $this->shortvideo_company_model->changeData($company);
                $where[] = ['a.company_id','in',$company_id];
            }

            //默认排序
            $order = $order?$order:'visitor_user';
            $By = $By?$By:'desc';

            $list = $this->model->staffUserList($where,$this->page_size,$order,$By);
            if(!empty($list['data'])){
                foreach ($list['data'] as $key=>$val){
                    if(empty($list['data'][$key]['avatar'])) $list['data'][$key]['avatar'] = 'https://lbqnyv2.migugu.com/defaultAvatar.png';
                }
            }
        }else if($type == 2){
            if($name){
                $where[] = ['a.nickName' ,'like' ,"%{$name}%"];
            }
            //默认排序
            $order = $order?$order:'browse_count';
            $By = $By?$By:'desc';
            $list = $this->model->userList($where,$this->page_size,$order,$By);
            foreach ($list['data'] as $key=>$val){
                if(empty($list['data'][$key]['avatarUrl'])) $list['data'][$key]['avatarUrl'] = 'https://lbqnyv2.migugu.com/defaultAvatar.png';
            }
        }

        foreach ($list['data'] as $key=>$val){
            $h_time = gmdate('H',$val['browse_time']); //时
            $i_time = gmdate('i',$val['browse_time']); //分
            $s_time = gmdate('s',$val['browse_time']); //秒

            $h_time = $h_time != '00'?$h_time.' 时 ':'';
            $i_time = $i_time != '00'?$i_time.' 分 ':'';
            $s_time = $s_time != '00'?$s_time.' 秒 ':'';

            $list['data'][$key]['browse_time'] = $h_time.$i_time.$s_time;
        }

        return $this->success($list);
    }

    /**
     **@param array $where 基础条件
     * @param bool $send
     * @param bool $goods
     * @param bool $consult
     * @param bool $phone
     * @param bool $wechat
     * @功能说明: 复用统计 --查询
     * @author lichuanming
     * @DataTime: 2020/5/20 10:42
     */
    public function publicCount($where = [],$send = false,$goods = false,$consult = false,$phone = false,$wechat = false){
        unset($where['type']);
        $visitorWhere = $wechatWhere = $phoneWhere = $consultWhere = $sendWhere = $goodsWhere = $where;
        $data = [];
        if(!empty($where)){
            $visitorWhere[] = ['type','=',1];
            $visitorWhereN = $visitorWhere;
            $visitorWhereN[] = ['first','=',1]; //在这个事件段首次进来的用户
            $data = [
                'browse_num' => $this->model_browse->where($where)->count(), //浏览总次数
                'browse_user'  => $this->model_browse->getCount($where), //浏览总人数

                'visitor_num' => $this->model_visitors->getCount($visitorWhere,''), //获客总次数
                'visitor_user'  => $this->model_visitors->getGroupCount($visitorWhereN), //获客总人数
            ];
        }

        //咨询信息--
        $data_consult = [];
        if($consult){
            $consultWhere[] = ['mode' ,'=' ,1];
            $data_consult = [
                'consult_num' => $this->model_visitors->getCount($consultWhere,''), //咨询点击次数
                'consult_user'  => $this->model_visitors->getGroupCount($consultWhere), //咨询点击人数
            ];
        }

        //拨打电话--
        $data_phone = [];
        if($phone){
            $phoneWhere[] = ['mode' ,'=' ,2];
            $data_phone = [
                'phone_num' => $this->model_visitors->getCount($phoneWhere,''), //拨打电话被点击次数
                'phone_user'  => $this->model_visitors->getGroupCount($phoneWhere), //拨打电话点击人数
            ];
        }

        //复制微信号
        $data_wechat = [];
        if($wechat){
            $wechatWhere[] = ['mode' ,'=' ,3];
            $data_wechat = [
                'wechat_num' => $this->model_visitors->getCount($wechatWhere,''), //复制微信号次数
                'wechat_user'  => $this->model_visitors->getGroupCount($wechatWhere), //复制微信号人数
            ];
        }

        //用户转发
        $data_send = [];
        if($send){
            $sendWhere[] = ['mode' ,'=' ,4];
            $data_send = [
                'send_num' => $this->model_visitors->getCount($sendWhere,''), //转发总次数
                'send_user'  => $this->model_visitors->getGroupCount($sendWhere), //转发总人数
            ];
        }

        //商品点击
        $data_goods = [];
        if($goods){
            $goodsWhere[] = ['mode' ,'=' ,5];
            $data_goods = [
                'goods_num' => $this->model_visitors->getCount($goodsWhere,''), //商品被点击次数
                'goods_user'  => $this->model_visitors->getGroupCount($goodsWhere), //商品点击人数
            ];
        }

        //拼接多个数组
        $resData = $data + $data_send + $data_goods + $data_consult + $data_phone + $data_wechat;
        return $resData;
    }

}